package cn.itcast.nems.order.web.controller.b;

import cn.itcast.ic.common.bean.BizError;
import cn.itcast.ic.common.bean.Page;
import cn.itcast.ic.common.exception.BizException;
import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.account.AccountInfo;
import cn.itcast.nems.common.web.vo.BasePageRequest;
import cn.itcast.nems.manager.msas.MsasManager;
import cn.itcast.nems.manager.redis.RedisUtil;
import cn.itcast.nems.order.dao.dataobject.OrderRefundDO;
import cn.itcast.nems.order.dto.OrderRefundDTO;
import cn.itcast.nems.order.service.OrderRefundReverseService;
import cn.itcast.nems.order.service.OrderRefundService;
import cn.itcast.nems.studentrecord.dao.dataobject.StudentRecordInfoDO;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单退费相关的
 */
@Slf4j
@RestController("bOrderRefundController")
@RequestMapping("/b/order/refund")
public class OrderRefundController {
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private OrderRefundReverseService orderRefundReverseService;
    @Autowired
    private StudentRecordService studentRecordService;
    @Autowired
    private MsasManager msasManager;
    @Autowired
    private RedisUtil redisUtil;

//    // 添加回冲
//    @PostMapping("/reverse")
//    public ResponseEntity<String> addReverse(@RequestBody OrderRefundReverseVO reverseVO) {
//        final BigDecimal amount = reverseVO.getAmount();
//        if (amount == null || amount.compareTo(BigDecimal.ZERO) == 0) {
//            throw new BizException(BizError.parameterError("冲回金额不能是空或0"));
//        }
//        OrderRefundReverseDTO dto = new OrderRefundReverseDTO();
//        BeanUtils.copyProperties(reverseVO, dto);
//        final AccountInfo info = AccountHolder.getRequiredAccountInfo();
//        dto.setCreatedByName(info.getName());
//        String id = this.orderRefundReverseService.addOrderRefundReverse(dto);
//        log.info("addReverse finish!");
//        return ResponseEntity.ok().body(id);
//    }

    @GetMapping("/{orderRefundId}/back")
    public ResponseEntity<?> orderRefundBack(@PathVariable("orderRefundId") String orderRefundId) {
        return ResponseEntity.ok(orderRefundReverseService.orderRefundBack(orderRefundId));
    }

    // 新增接口：分页查询退单列表
    @PostMapping("/page/list")
    public ResponseEntity<Page<OrderRefundDO>> findPageList(@RequestBody BasePageRequest<OrderRefundDO> queryParam) {
        queryParam.convert();
        log.info("[分页查询退单列表] 请求参数: {} ", queryParam);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OrderRefundDO> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        page.setCurrent(queryParam.getPageNumber());
        page.setSize(queryParam.getPageSize());
        IPage<OrderRefundDO> data = orderRefundService.listPage(page, queryParam.getCondition());
        if (data == null) {
            return ResponseEntity.ok().body(Page.of(Long.valueOf(queryParam.getPageNumber()).intValue(),
                    Long.valueOf(queryParam.getPageSize()).intValue(),
                    0, null));
        }
        Page<OrderRefundDO> pageData = Page.of(Long.valueOf(data.getCurrent()).intValue(),
                Long.valueOf(data.getSize()).intValue(),
                Long.valueOf(data.getTotal()).intValue(), data.getRecords());
        return ResponseEntity.ok().body(pageData);
    }

    // 新增接口：查看退单详情
    @GetMapping("/{orderRefundId}")
    public ResponseEntity<Map<String, Object>> orderInfo(@PathVariable("orderRefundId") String orderRefundId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> orderRefundInfo = orderRefundService.orderRefundInfo(orderRefundId);
        Assert.notNull(orderRefundInfo, "退单不存在");
        map.put("orderRefundInfo", orderRefundInfo);
        String studentRecordId = (String) orderRefundInfo.get("student_record_id");
        Integer clazzId = (Integer) orderRefundInfo.get("clazz_id");
        List<StudentRecordInfoDO> studentRecordInfoDOS = studentRecordService.listStudentRecordInfoByjournalRefundId(studentRecordId, clazzId);
        // TODO 退费班级信息
        map.put("refundClazzs", studentRecordInfoDOS);
        return ResponseEntity.ok(map);
    }

    // 新增接口：添加退单-查询退款付款渠道列表
    @GetMapping("/paymentchannels/{schoolId}")
    public ResponseEntity<List<Map<String, Object>>> paymentchannels(@PathVariable("schoolId") String schoolId) {
        return ResponseEntity.ok(orderRefundService.paymentchannels(schoolId));
    }

    // 新增接口：添加退单-获取退费类型列表
    @GetMapping("/incomeexpenses/types")
    public ResponseEntity<List<Map<String, Object>>> incomeexpensestypes() {
        return ResponseEntity.ok(orderRefundService.incomeexpensestypes());
    }

    // 新增接口：添加退单-获取付费方式列表
    @GetMapping("/studentcost/types")
    public ResponseEntity<List<Map<String, Object>>> studentCostTypes() {
        return ResponseEntity.ok(orderRefundService.studentCostTypes());
    }

    // 新增接口：添加退单-确认保存退单
    @PostMapping("/create")
    public ResponseEntity<Boolean> createOrderRefund(@RequestBody OrderRefundDTO orderRefundDTO) {
        final AccountInfo info = AccountHolder.getRequiredAccountInfo();
        String key = String.format("CREATE_ORDER_REFUND:%s", info);
        try {
            if (redisUtil.get(key) != null) {
                throw new BizException(BizError.BAD_REQUEST.getStatus(), BizError.BAD_REQUEST.getCode(), "重复操作");
            }
            redisUtil.set(key, true, 60);
            orderRefundDTO.setCreatedBy(info.getEmail());
            orderRefundDTO.setRefundOperatorEmail(info.getEmail());
            orderRefundDTO.setCreatedByName(info.getName());
            orderRefundDTO.setRefundOperatorName(info.getName());
            orderRefundService.createOrderRefund(orderRefundDTO);
        } catch (Exception e) {
            redisUtil.del(key);
            log.error("[添加退单-确认保存退单] 异常: {} ", e.toString());
            throw new BizException(new BizError(HttpStatus.SC_BAD_REQUEST, "SERVER_REQUEST_ERROR", e.getMessage()));
        } finally {
            redisUtil.del(key);
        }
        return ResponseEntity.ok().body(true);
    }

    @PostMapping("/clazzes")
    public ResponseEntity<Page<Map>> searchClazzes(@RequestBody BasePageRequest<OrderRefundDO> params) {
        params.convert(50);
        // 页数
        Integer pageNumber = params.getPageNumber();
        Integer pageSize = params.getPageSize();
        // 条件
        OrderRefundDO condition = params.getCondition();
        return ResponseEntity.ok(orderRefundService.searchClazzes(pageNumber, pageSize, condition));
    }
}
